package com.wc;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;

public class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

    private IntWritable result = new IntWritable();

    /*
    相同的key为一组 ，这一组数据调用一次reduce
    hello 1
    hello 1
    hello 1
    hello 1
     */
    public void reduce(Text key, Iterable<IntWritable> values,
                       Context context) throws IOException, InterruptedException {

        // System.out.println("reduce- key:" + key.toString() + ",value:" + values.iterator().next());

        int sum = 0;
        Iterator<IntWritable> iterator = values.iterator();
        while (iterator.hasNext()) {
            // 等同于下面的遍历效果
            IntWritable value = iterator.next();
            sum += value.get();
        }

        result.set(sum);
        context.write(key, result);
    }

}
